// 导入TOKEN_NAME常量，与request.js保持一致
const TOKEN_NAME = 'wn_satoken';

export default {
  namespaced: true,
  state: {
    token: uni.getStorageSync(TOKEN_NAME) || '',
    userInfo: uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')) : null,
    isLogin: Boolean(uni.getStorageSync(TOKEN_NAME))
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      state.isLogin = Boolean(token)
      uni.setStorageSync(TOKEN_NAME, token)
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      uni.setStorageSync('userInfo', JSON.stringify(userInfo))
    },
    SET_LOGIN_STATUS(state, status) {
      state.isLogin = status
    },
    LOGOUT(state) {
      state.token = ''
      state.userInfo = null
      state.isLogin = false
      uni.removeStorageSync(TOKEN_NAME)
      uni.removeStorageSync('userInfo')
    }
  },
  actions: {
    // 设置登录状态
    setLoginStatus({ commit }, status) {
      commit('SET_LOGIN_STATUS', status)
    },
    
    // 设置用户信息
    setUserInfo({ commit }, userInfo) {
      commit('SET_USER_INFO', userInfo)
    },
    
    // 登录
    login({ commit }, params) {
      return new Promise((resolve, reject) => {
        this._vm.$http.post('/api/user/login', params)
          .then(res => {
            commit('SET_TOKEN', res.token)
            commit('SET_USER_INFO', res)
            resolve(res)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    
    // 获取用户信息
    getUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (!state.token) {
          reject('未登录')
          return
        }
        
        this._vm.$http.get('/api/user/info')
          .then(res => {
            commit('SET_USER_INFO', res)
            resolve(res)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    
    // 更新用户信息
    updateUserInfo({ commit }, params) {
      return new Promise((resolve, reject) => {
        this._vm.$http.put('/api/user/info', params)
          .then(res => {
            commit('SET_USER_INFO', res)
            resolve(res)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    
    // 退出登录
    logout({ commit }) {
      commit('LOGOUT')
      return Promise.resolve()
    }
  },
  getters: {
    isLogin: state => state.isLogin,
    userInfo: state => state.userInfo || {},
    token: state => state.token
  }
} 